package com.jf.orther.speech_to_text.vosk;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.wav.WavFileReader;
import org.vosk.Model;
import org.vosk.Recognizer;

import javax.sound.sampled.AudioSystem;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * java语音转文字
 * https://blog.csdn.net/qq_35132089/article/details/127069618
 * https://alphacephei.com/vosk/models
 *
 * 处理简单的可以，复杂的还是不得行
 *
 */
public class SpeechToText {
    public static void main(String[] args) {
	processFile("C:\\Users\\hz21087153\\Downloads\\vosk-model-small-cn-0.22", new File("01.wav"));
//	processFile("C:\\Users\\hz21087153\\Downloads\\vosk-model-small-cn-0.22", new File("rGQAWGO3zQiATradAABKQAAH_Ik518.wav"));

    }

    private static void processFile(String modelPath, File file) {
	try (Model model = new Model(modelPath);//该段是模型地址
	     InputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(file))); //该段是要转的语言文件，仅支持wav
	     Recognizer recognizer = new Recognizer(model, getSampleRate(file))) { //该段中12000是语言频率(Hz)，需要大于8000，可以自行调整

	    int bytes;
	    byte[] b = new byte[4096];
	    while ((bytes = ais.read(b)) >= 0) {
		recognizer.acceptWaveForm(b, bytes);
	    }
	    System.out.println(file.getName());
	    System.out.println(recognizer.getFinalResult() + System.lineSeparator());
	} catch (Exception e) {

	    e.printStackTrace();
	}
    }

    /**
     * 获取音频文件的采样率
     */
    private static Float getSampleRate(File file) throws Exception {
	WavFileReader fileReader = new WavFileReader();
	AudioFile audioFile = fileReader.read(file);
	String sampleRate = audioFile.getAudioHeader().getSampleRate();
	return Float.parseFloat(sampleRate);
    }
}
